package com.raymond.cmpp.common.codec.encodeing;

import com.raymond.cmpp.common.codec.BaseCodec;
import com.raymond.cmpp.common.enums.CommandIdType;
import com.raymond.cmpp.common.msg.BaseMessage;
import com.raymond.cmpp.common.msg.MsgHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * 编码器
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-08-05 14:55
 */
public abstract class BaseEncoder extends BaseCodec {

    public void encode(ChannelHandlerContext ctx, BaseMessage msg, ByteBuf out) throws Exception {
        byte[] body = encode0(msg);
        if (msg.getCommandId() != CommandIdType.PACK_REQ.getCommandId()) {
            out.writeInt(body.length + MsgHead.getHeadLength());
            out.writeInt(msg.getCommandId());
            out.writeInt(msg.getSequenceId());
        }
        out.writeBytes(body);
    }

    /**
     * 消息编码
     * @param msg 响应提
     * @return 请求报文
     * @throws Exception 异常
     */
    public abstract byte[] encode0(BaseMessage msg) throws Exception;
}
